<?php
/*
 * @Author: your name
 * @Date: 2020-04-24 13:41:08
 * @LastEditTime: 2020-04-28 16:26:09
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \ztaudio-activity\app\Http\Controllers\FiveController.php
 */

namespace App\Http\Controllers;

use App\Http\Model\Config;
use App\Http\Model\Gift;
use App\Http\Model\Hint;
use App\Http\Model\OutJson;
use App\Http\Model\User;
use App\Http\Model\UserM;
use Laravel\Lumen\Routing\Controller as BaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

/*
 * 充值赠送钻石
 * */

class FiveController extends BaseController
{
    protected $model;
    protected $configModel;
    protected $gift_model;
    protected $user_model;

    CONST CACHE_RECEIVER_FIRST_KEY = "REDIS:FIVE:RECEIVER_1:";      // 魅力榜
    CONST CACHE_SENDER_FIRST_KEY = "REDIS:FIVE:SENDER_1:";          // 财富榜
    CONST CACHE_RECEIVERWEB_FIRST_KEY = "REDIS:FIVE:RECEIVERWEB_1:";      //WEB 投票

    CONST CACHE_STAND_FOR_ELECTION = "CACHE:STAND_FOR_ELECTION";  // 胜出者
    CONST CACHE_SENDER_LIMIT_OF_DAY = "CACHE:FIVE:SENDER:LIMIT:"; // 投票限制
    CONST CACHE_NO_STAND_FOR_ELECTION = "CACHE:NO:STAND_FOR_ELECTION";
    CONST DATE_ARRAY = [
      [ '20200525', '20200601' ],//海选
      [ '20200602', '20200608' ],//晋级
      [ '20200609', '20200615' ],//复活
      [ '20200616', '20200622' ]//总决
    ];
    
    public function __construct()
    {
        // $this->configModel = $config;
        $this->gift_model = new Gift();
        $this->user_model = new UserM();
    }

    public function assignAction($body = []) {
      
      // $body_json = '{"room_id":0,"gift_id":185,"user_id":70,"to_user_id_array":[125,126],"gift_num":1,"create":1587634272,"type":0,"consumer_type":1}';
      // $body = json_decode($body_json, true);
      // $body = json_decode($body, true);

      //消费执行时间
      if(time()<1590562500){ return false;}
      $gift_id = $body['gift_id'];
      $user_id = $body['user_id'];    // 送礼物者
      $to_user_id_array = $body['to_user_id_array'];  // 收礼物者
      $gift_num = $body['gift_num'];                  // 礼物数
      $type = 0; //礼物投票
      $stage = $this->whichStage();

      if($stage === -1) {
        write_log('fiveConsumer', 'timeError', "活动未开始");
        return false;
      }

      if($stage === -2) {
        write_log('fiveConsumer', 'timeError', "活动已结束");
        return false;
      }
      $vote_num = $this->user_model->voiceCount($to_user_id_array);
      if(!$vote_num){
        return false;
      }
      $to_user_id_array = array_column($vote_num, 'user_id');
      $to_user_id_array = array_unique($to_user_id_array);
      $gift_id_arr = [185,186,187,188];
      //gift_id 指定联赛票判断
      if(!in_array($gift_id,$gift_id_arr)){
        return false;
      }
      // 送礼物结合
      $sender_key = self::CACHE_SENDER_FIRST_KEY.$stage;
      $sender_key_sum = self::CACHE_SENDER_FIRST_KEY.'SUM';
      // 送出礼物者票数增加
      $sender_gift_num = count($to_user_id_array)*$gift_num;
      if($stage == 0 && $gift_id_arr[0]==$gift_id){
        Redis::ZINCRBY($sender_key, $sender_gift_num, $user_id);
        Redis::ZINCRBY($sender_key_sum, $sender_gift_num, $user_id);
        $this->vote($stage, $to_user_id_array, $gift_num, $user_id );

      }elseif($stage == 1 && $gift_id_arr[1]==$gift_id ){
        Redis::ZINCRBY($sender_key, $sender_gift_num, $user_id);
        Redis::ZINCRBY($sender_key_sum, $sender_gift_num, $user_id);
        $this->vote($stage, $to_user_id_array, $gift_num, $user_id );

      }elseif($stage == 2 && $gift_id_arr[2]==$gift_id ){
        Redis::ZINCRBY($sender_key, $sender_gift_num, $user_id);
        Redis::ZINCRBY($sender_key_sum, $sender_gift_num, $user_id);
        $this->vote($stage, $to_user_id_array, $gift_num, $user_id );

      }elseif($stage == 3 && $gift_id_arr[3]==$gift_id ){
        Redis::ZINCRBY($sender_key, $sender_gift_num, $user_id);
        Redis::ZINCRBY($sender_key_sum, $sender_gift_num, $user_id);
        $this->vote($stage, $to_user_id_array, $gift_num, $user_id );

      }else{
        return false;
      }
      
    }
    public function getSenderList(){
      $data = $this->user_model->getSenderList();
      $sender_key = self::CACHE_SENDER_FIRST_KEY.'0';
      $sender_key_sum = self::CACHE_SENDER_FIRST_KEY.'SUM';

      foreach($data as $item){
        Redis::ZADD($sender_key, $item['gift_num'], $item['from_user_id']);
        Redis::ZADD($sender_key_sum, $item['gift_num'], $item['from_user_id']);
      }
      $data_1 = $this->user_model->getSenderList1();
      $receiver_key = self::CACHE_RECEIVER_FIRST_KEY.'0';
      //收到总票数
      $receiver_sum = self::CACHE_RECEIVER_FIRST_KEY.'SUM'; 
      foreach($data_1 as $item){
        Redis::ZADD($receiver_key, $item['gift_num'], $item['user_id']);
        //总票数
        Redis::ZADD($receiver_sum, $item['gift_num'], $item['user_id']);
      }
    }
    /**
     * 联赛阶段
     * 
     * @return void 0 海选赛; 1 竞技赛; 2 复活赛; 3 总决赛; -1 活动未开始; -2 活动已结束
     */
    private function whichStage() {
      // $now = date('Ymd', strtotime('2020-05-26'));//1/9/17/25
      $now = date('Ymd',time());
      if($now < self::DATE_ARRAY[0][0]) {
        return -1;
      }

      if($now >= self::DATE_ARRAY[0][0] && $now <= self::DATE_ARRAY[0][1]) {
        return 0;
      }
      if($now >= self::DATE_ARRAY[1][0] && $now <= self::DATE_ARRAY[1][1]) {
        return 1;
      }
      if($now >= self::DATE_ARRAY[2][0] && $now <= self::DATE_ARRAY[2][1]) {
        return 2;
      }
      if($now >= self::DATE_ARRAY[3][0] && $now <= self::DATE_ARRAY[3][1]) {
        return 3;
      }
      return -2;
    }

    /**
     * 海选赛竞级竞级赛
     *
     * @return void
     */
    public function firstStage() {
       // 海选赛前 60 名 
       $receiver_key = self::CACHE_RECEIVER_FIRST_KEY. '0';  
       $res = Redis::zrevrangebyscore($receiver_key, '+inf', '-inf', array('withscores' =>true,'limit'=>array(0, 60)) );
      //调试10名
      //  $res = Redis::zrevrangebyscore($receiver_key, '+inf', '-inf', array('withscores' =>true,'limit'=>array(0, 10)) );
       $keys = array_keys($res);

       foreach($keys as $user_id) {
         $this->gift_model->standForElection($user_id);
       }
       
       // 复活赛选手
       $vote_num = $this->user_model->voiceAll($keys);
       if(!$vote_num){
         return fasle;
       }
       $user_id_array = array_column($vote_num, 'user_id');
       $user_id_array = array_diff($user_id_array,$keys);
       
       $user_id_array = array_unique($user_id_array);
       foreach($user_id_array as $user_id) {
         $this->gift_model->addLoser($user_id);
       }


      //  $res = Redis::zrevrangebyscore($receiver_key, '+inf', '-inf', array('withscores' =>true,'limit'=>array(60, -1)) );
       //调试
      //  $res = Redis::zrevrangebyscore($receiver_key, '+inf', '-inf', array('withscores' =>true,'limit'=>array(10, -1)) );
      //  $keys = array_keys($res);
      //  foreach($keys as $user_id) {
      //    $this->gift_model->addLoser($user_id);
      //  }

       Log::debug("海选赛前 60 名已选出");
    }

    /**
     * 竞级赛胜出选手
     *
     * @return void
     */
    public function secondStage() {

      // 竞级赛前 30 名
      $receiver_key = self::CACHE_RECEIVER_FIRST_KEY. '1'; 
      $res = Redis::zrevrangebyscore($receiver_key, '+inf', '-inf', array('withscores' =>true,'limit'=>array(0, 30)) );
      
      // 清空上一轮选手
      $this->gift_model->emptyStandForElection();

      $keys = array_keys($res);
      foreach($keys as $user_id) {
        $this->gift_model->standForElection($user_id);
      }

      Log::debug("竞级赛前 30 名已选出");
    }

    /**
     * 复活赛胜出选手
     *
     * @return void
     */
    public function thirdStage() {

      // 复活赛前 10 名
      $receiver_key = self::CACHE_RECEIVER_FIRST_KEY. '2'; 
      $res = Redis::zrevrangebyscore($receiver_key, '+inf', '-inf', array('withscores' =>true,'limit'=>array(0, 10)) );
      // $res = Redis::zrevrangebyscore($receiver_key, '+inf', '-inf', array('withscores' =>true,'limit'=>array(0, 2)) );
      $keys = array_keys($res);
      foreach($keys as $user_id) {
        $this->gift_model->standForElection($user_id);
      }

      Log::debug("复活赛前 10 名已选出");
    }

    /**
     * 复活赛胜出选手
     *
     * @return void
     */
    public function lastStage() {

      // 复活赛前 10 名
      $receiver_key = self::CACHE_RECEIVER_FIRST_KEY. '3'; 
      $res = Redis::zrevrangebyscore($receiver_key, '+inf', '-inf', array('withscores' =>true,'limit'=>array(0, 10)) );
      $keys = array_keys($res);
      foreach($keys as $user_id) {
        $this->gift_model->standForElection($user_id);
      }

      Log::debug("复活赛前 10 名已选出");
    }

    /**
     * 竞级榜
     *
     * @param Request $request
     * @return void
     */
    public function winnerList(Request $request) {
      $stage = $request->get('stage');
      if($stage == 4 || $stage == 3 ||$stage == 1){
        $receiver_key = self::CACHE_RECEIVER_FIRST_KEY. ($stage - 1);
      }else{
        $receiver_key = self::CACHE_RECEIVER_FIRST_KEY. ($stage - 2);
      }
      // var_dump($receiver_key);
      $stageNow = $this->whichStage();
      if(!$stageNow == 3){
        if(!Redis::EXISTS($receiver_key)) return  OutJson::toJson(200, '成功');
      }
      

      // $limit = [60, 30, 10, 10][$stage - 1];
      //调试
      $limit = [60, 30, 30, -1][$stage - 1];
      $res = Redis::zrevrangebyscore($receiver_key, '+inf', '-inf', array('withscores' =>true,'limit'=>array(0, $limit)) );
      
      $receiver_key_next = self::CACHE_RECEIVER_FIRST_KEY. ($stage - 1);
      
      $user_ids = array_keys($res);
      //下一阶段开始
      if(Redis::EXISTS($receiver_key_next)){
        $res_next = Redis::zrevrangebyscore($receiver_key_next, '+inf', '-inf', array('withscores' =>true,'limit'=>array(0, $limit)) );
        foreach($res as $key=>$value){
          $arr[$key] = 0;  
                        
        }      
        $res = $res_next+$arr;
        $user_ids = array_keys($res);
      }
      $loser = Redis::SMEMBERS(self::CACHE_NO_STAND_FOR_ELECTION);
      if($stage == 3 && empty($res)){$user_ids = $loser;}
      //总决
      if($stage == 4 && empty($res)){$user_ids = Redis::SMEMBERS(self::CACHE_STAND_FOR_ELECTION);}

      $winners = $this->user_model->getFiveWinners($user_ids)->toArray();
      foreach($winners as &$user) {
       $user['score'] = $res[$user['user_id']] ?? 0;
      }
      unset($user);

      $ww = array_multisort(array_column($winners,'score'),SORT_DESC,$winners);
      $ww = $winners;
      // var_dump($ww);die;
      OutJson::toJson(200, '成功', array_values($ww));
    }
    /**
     * 富豪榜
     *
     * @return void
     */
    public function richList_1(Request $request) {
      $stage = $request->get('stage');
       // 富豪榜前 10 名
       $receiver_key = self::CACHE_SENDER_FIRST_KEY. ($stage - 1);   
       $receiver_key_sum = self::CACHE_SENDER_FIRST_KEY. 'SUM';  

        $redisKey = $receiver_key;
        if (Redis::exists($redisKey)) {
            $data = json_decode(Redis::get($redisKey), true);
            return $data;
        }
        $winners = $this->user_model->getFiveRich();
        $gift_id_arr = [185,186,187,188];
        
        // $data = self::objToArray($data);
 
        Redis::setex($redisKey, 600, json_encode($data, JSON_UNESCAPED_UNICODE));
        Redis::ZINCRBY($receiver_key_sum, $sender_gift_num, $user_id);

    return $data;
  }
    /**
     * 富豪榜
     *
     * @return void
     */
    public function richList(Request $request) {
      $stage = $request->get('stage');
       // 富豪榜前 10 名
      //  $receiver_key = self::CACHE_SENDER_FIRST_KEY. ($stage - 1);  
      //  if(!Redis::EXISTS($receiver_key)) return  OutJson::toJson(200, '成功');
       
      //  $res = Redis::zrevrangebyscore($receiver_key, '+inf', '-inf', array('withscores' =>true,'limit'=>array(0, 30)) );
      $receiver_key = self::CACHE_SENDER_FIRST_KEY. 'SUM';  
       if(!Redis::EXISTS($receiver_key)) return  OutJson::toJson(200, '成功');
       
       $res = Redis::zrevrangebyscore($receiver_key, '+inf', '-inf', array('withscores' =>true,'limit'=>array(0, 30)) );
       $user_ids = array_keys($res);
       
       $winners = $this->user_model->getFiveWinners($user_ids)->toArray();
       foreach($winners as &$user) {
        $user['score'] = $res[$user['user_id']];
       }
       unset($user);
      //  $ww = array_column($winners,null,'score');
      //  krsort($ww);
      $ww = array_multisort(array_column($winners,'score'),SORT_DESC,$winners);
      $ww = $winners;
       OutJson::toJson(200, '成功', array_values($ww));
      //  OutJson::toJson(200, '成功', $winners);
    }

    /**
     * 语音列表
     *
     * @param Request $request
     * @return void
     */
    public function voiceList(Request $request) {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 8);
        $search = $request->get('search','');
        $stage = $request->get('stage','');
        $search?$search = "uuid ='$search'": '';
        $stageNow = $this->whichStage();
        if( $stageNow > 0){  
          if($stage == 4 && $stageNow !== 3){
           OutJson::toJson(200, '决赛未开启' );
           exit;
          }elseif($stage == 4 && $stageNow == 3){

          }else{
            // OutJson::toJson(200, '海选已结束' );
           exit;
          }
        }

        if($stage == 4 && $stageNow ==3 && $search ==''){
          //胜出榜取出数据
          $receiver_key = self::CACHE_STAND_FOR_ELECTION;
          $res = Redis::SMEMBERS($receiver_key);
          $user_ids = $res;
          // var_dump($user_ids);die;
          
          if(is_array($user_ids)){
            $sql = 'user_id=';
            for ($i=0; $i < count($user_ids); $i++) { 
              if($i<count($user_ids)-1){
                $sql .= $user_ids[$i].' or user_id = ';
              }else{
                $sql .= $user_ids[$i];
              }
              
            }
          }
          $search = $sql;
        }
        $page = ($page - 1) * $limit;
        $voices = [];
        //用户信息 音频  图片
        $voices = $this->user_model->getFiveVoice($page, $limit,$search);  
        // dd($voices);
        //收到总票数
        $receiver_sum = self::CACHE_RECEIVER_FIRST_KEY.'SUM'; 
        for ($i=0; $i < count($voices); $i++) { 
          $voices[$i]['stage'] = $stageNow;
          //总决
          if($stageNow == 3){
            $receiver_key = self::CACHE_RECEIVER_FIRST_KEY.$stageNow; 
            
            for ($i=0; $i < count($voices); $i++) { 
              $voices[$i]['stage'] = $stageNow;
              $res = Redis::ZSCORE($receiver_key ,$voices[$i]['user_id']);
              if(!$res){
                $voices[$i]['vote_sum_num'] = 0;
              }else{
                $voices[$i]['vote_sum_num'] = $res;
              }
            }
          }else{
            $res = Redis::ZSCORE($receiver_sum,$voices[$i]['user_id']);
            if(!$res){
              $voices[$i]['vote_sum_num'] = 0;
            }else{
              $voices[$i]['vote_sum_num'] = $res;
            }
          }
          
        }

        //aaaaab
        OutJson::toJson(200, '成功', $voices);

    }

    public function toVote(Request $request) {
      $to_user_id = $request->post('to_user_id', 0);
      $vote_num = $request->post('vote_num');
      $stage = $this->whichStage();
      $user_id = $request->post('user_id', 0);
      $formstage = $request->post('stage');

      //消费执行时间
      if(time()<1590562500){ return false;}

      if($formstage == 4 && $stage !==3){OutJson::toJson(200, '决赛未开启'); }
      if($stage == 1 || $stage ==2){OutJson::toJson(200, '海选已结束'); }
      //海选区投票
      $bool = $this->gift_model->isStandForElection($to_user_id);
      // var_dump($bool);die;
      if(!$bool && $stage == 3){OutJson::toJson(200, '选手不在决赛名单');}
      //每日剩余票数

        $day = date('Ymd');
        $key = self::CACHE_SENDER_LIMIT_OF_DAY.$day.':'. $user_id;
        if(Redis::EXISTS($key)) {
          $init_vote_num = Redis::GET($key);          
          $init_vote_num = $init_vote_num - $vote_num;
          if($init_vote_num<0) OutJson::toJson(201, '余票不足',$init_vote_num);
          Redis::SET($key, $init_vote_num);
        }        

      if($user_id == $to_user_id){
        OutJson::toJson(200, '投票不符规则',$vote_num);
      }else{
        //web 投票榜
        $receiver_key = self::CACHE_RECEIVERWEB_FIRST_KEY.$stage; 
        Redis::ZINCRBY($receiver_key, $vote_num, $user_id);
        $this->vote($stage, [ $to_user_id ], $vote_num, $user_id);
        OutJson::toJson(200, '成功',$vote_num);
      }
      
    }

    public function initVoteNum(Request $request) {
      $user_id = $request->get('user_id');
      $day = date('Ymd');
      $key = self::CACHE_SENDER_LIMIT_OF_DAY.$day.':'. $user_id;

      $vote_num = 100;
      if(Redis::EXISTS($key)) {
        $vote_num = Redis::GET($key);
      } else {
        Redis::SET($key, 100);
      }
      OutJson::toJson(200, '成功', $vote_num);
    }

    /**
     * 投票
     *
     * @param [type] $stage                 // 阶段标识 0 海选; 1 竞级; 2 复活; 3 总决赛
     * @param [type] $to_user_id_array      // 接收礼物者
     * @param [type] $gift_num              // 礼物数
     * @param [type] $user_id               // 送礼物者
     * @return void
     */
    private function vote($stage, $to_user_id_array, $gift_num, $user_id) {
      // 收礼物集合
      $receiver_key = self::CACHE_RECEIVER_FIRST_KEY.$stage;  
      // 送礼物结合
      // $sender_key = self::CACHE_SENDER_FIRST_KEY.$stage;
      //收到总票数
      $receiver_sum = self::CACHE_RECEIVER_FIRST_KEY.'SUM'; 
      // var_dump($receiver_key);die;
      // 海选赛
      if($stage === 0) {
          // 接收礼物者票数增加
        foreach($to_user_id_array as $receiver_id) {
          Redis::ZINCRBY($receiver_key, $gift_num, $receiver_id);
          //总票数
          Redis::ZINCRBY($receiver_sum, $gift_num, $receiver_id);
        }
      }

      // 复活赛
      if($stage === 2) {
        foreach($to_user_id_array as $receiver_id) {
          if($this->gift_model->isLoser($receiver_id)) {
            Redis::ZINCRBY($receiver_key, $gift_num, $receiver_id);
            //总票数
            Redis::ZINCRBY($receiver_sum, $gift_num, $receiver_id);
          }
        }
      }
      // var_dump($stage);
      // 竞级赛 总决赛
      if($stage === 1 || $stage === 3) {
        foreach($to_user_id_array as $receiver_id) {
          // var_dump($this->gift_model->isStandForElection($user_id));
          if($this->gift_model->isStandForElection($receiver_id)) {
            // var_dump($receiver_id);die;
            Redis::ZINCRBY($receiver_key, $gift_num, $receiver_id);
            //总票数
            Redis::ZINCRBY($receiver_sum, $gift_num, $receiver_id);
          }
        }
      }
      // 送出礼物者票数增加
      // $sender_gift_num = count($to_user_id_array)*$gift_num;
      // Redis::ZINCRBY($sender_key, $sender_gift_num, $user_id);
      
      
    }

    /**
     * 添加新用户手机号
     *
     * @param Request $request
     * @return void
     */
    public function bindPhone(Request $request) {
      $phone = $request->get('phone', '');
      $code = $request->get('code', '');
      $type = $request->get('type', '');
      $res = curl_request(env('KK_API_HOST') . '/user/convene/create', [ 'code' => $code, 'phone'=> $phone ,'type'=>1], 'urlencoded', 'GET');
      // $res = '{"code":0,"data":[],"msg":"\u6dfb\u52a0\u624b\u673a\u53f7\uff01"}' ;
      $res = json_decode($res, true);
      if($res['code'] === 0) {
        OutJson::toJson(200, '成功');
      }
      OutJson::toJson(201, $res['msg'] ?: '添加手机号！');
    
  }
}
